package com.yeziji.devops.utils;

import cn.hutool.core.util.URLUtil;
import com.yeziji.constant.VariousStrPool;
import com.yeziji.devops.annotation.DevopsService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.annotation.Annotation;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 轉換工具類
 *
 * @author hwy
 * @since 2024/08/01 20:59
 **/
@Slf4j
public class ParseUtils {
    /**
     * 根據 mysql 的鏈接獲取 database
     *
     * @param connection mysql 鏈接
     * @return {@link String} database name
     */
    public static String findDbByMysqlConnection(Connection connection) {
        String url;
        try {
            url = connection.getMetaData().getURL();
            // 构建格式化 url
            String normalize = URLUtil.normalize(url.replace("jdbc:mysql:", "http:"));
            // 转化为 httpUrl
            URL tempUrl = URLUtil.url(normalize);
            String path = tempUrl.getPath();
            return path.replace("/", "");
        } catch (SQLException e) {
            log.error("parse mysql connection failed: {}", e.getMessage(), e);
            return VariousStrPool.EMPTY;
        }
    }

    /**
     * 根据切入点转换为对应的注解
     *
     * @param pjp 切入点
     * @return {@link DevopsService}
     */
    public static <T extends Annotation> T getAnnotation(ProceedingJoinPoint pjp, Class<T> annotationClass) {
        Signature sig = pjp.getSignature();
        if (sig instanceof MethodSignature) {
            MethodSignature methodSig = (MethodSignature) sig;
            T annotation = methodSig.getMethod().getAnnotation(annotationClass);
            if (annotation != null) {
                return annotation;
            }
            // 也可以检查类上的注解
            Class<?> targetClass = pjp.getTarget().getClass();
            return targetClass.getAnnotation(annotationClass);
        }
        return null;
    }
}
